package com.therandoms.rtgdroid.steps;

import java.util.ArrayList;

import org.codepond.wizardroid.WizardStep;
import org.codepond.wizardroid.persistence.ContextVariable;
import org.therandoms.textgen.TextGeneratorDictionary;

import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import com.therandoms.rtgdroid.R;
import com.therandoms.rtgdroid.background.BitmapGenerationAsyncTask;
import com.therandoms.rtgdroid.background.MusicGeneratorAsyncTask;
import com.therandoms.rtgdroid.background.PastebinAsyncTask;

/**
 * This is the final step in the process!
 */
public class FinalResultsStep extends WizardStep {

	/**
	 * The number of default recurrences
	 */
	protected static final int DEFAULT_RECURRENCES = 5;

	/**
	 * Stores the words generated.
	 */
	@ContextVariable
	private ArrayList<String> outList;

	/**
	 * Stores the words to pass to the secondary substitution grammar.
	 */
	@ContextVariable
	private ArrayList<String> secondarySubstituteList;

	/**
	 * The dictionary for secondary substitution.
	 */
	@ContextVariable
	private TextGeneratorDictionary<String> secondarySubstitutionDictionary = new TextGeneratorDictionary<String>();

	/**
	 * The words after the secondary substitution
	 */
	private ArrayList<String> generatedList = new ArrayList<String>();

	/**
	 * The final text generated will go here.
	 */
	private TextView resultsView;

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.menu_random_text_results, menu);
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.action_share) {
			View share = getActivity().findViewById(R.id.action_share);
			PopupMenu popup = new PopupMenu(getActivity(), share);
			popup.getMenuInflater().inflate(R.menu.share_menu, popup.getMenu());

			popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
				public boolean onMenuItemClick(MenuItem item) {
					int id = item.getItemId();
					if (id == R.id.share_audio) {
						doAudioShare();
					} else if (id == R.id.share_image) {
						doImageShare();
					} else if (id == R.id.share_link) {
						doPastebinShare();
					} else {
						doTextShare();
					}

					return true;
				}
			});

			popup.show();
		}

		return super.onOptionsItemSelected(item);
	}

	/**
	 * Generates the block of text to share.
	 * 
	 * @return the block of text to share
	 */
	private String getTextToShare() {
		String text = getResources().getString(R.string.pastebin_preamble);
		text += "\n\n";
		text += resultsView.getText().toString();
		return text;
	}

	/**
	 * Shares the text
	 */
	private void doTextShare() {
		Intent intent = new Intent(Intent.ACTION_SEND);
		intent.setType("text/plain");
		intent.putExtra(Intent.EXTRA_TEXT, getTextToShare());
		startActivity(intent);
	}

	/**
	 * Does audio sharing.
	 */
	private void doAudioShare() {
		(new MusicGeneratorAsyncTask<String>() {
			@Override
			protected void onPostExecute(Uri result) {
				super.onPostExecute(result);

				// no result; paste issue
				if (result == null) {
					Toast.makeText(getActivity(), R.string.audio_error,
							Toast.LENGTH_SHORT).show();
				} else {
					Intent intent = new Intent(Intent.ACTION_SEND);
					intent.setType("application/x-midi");
					intent.putExtra(Intent.EXTRA_STREAM, result);
					startActivity(intent);
				}
			}
		}).execute(getTextToShare());
	}

	/**
	 * Does image sharing.
	 */
	private void doImageShare() {
		(new BitmapGenerationAsyncTask<String>() {
			@Override
			protected void onPostExecute(Uri result) {
				super.onPostExecute(result);

				// no result; paste issue
				if (result == null) {
					Toast.makeText(getActivity(), R.string.image_error,
							Toast.LENGTH_SHORT).show();
				} else {
					Intent intent = new Intent(Intent.ACTION_SEND);
					intent.setType("application/png");
					intent.putExtra(Intent.EXTRA_STREAM, result);
					startActivity(intent);
				}
			}
		}).execute(getTextToShare());
	}

	/**
	 * Creates a new pastebin and shares the link.
	 */
	private void doPastebinShare() {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(getActivity());

		String pastebinAPIKey = prefs.getString(
				"com.therandoms.rtgdroid.pastebin_api_key", null);
		(new PastebinAsyncTask() {

			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);

				// no result; paste issue
				if (result == null) {
					Toast.makeText(getActivity(), R.string.pastebin_error,
							Toast.LENGTH_SHORT).show();
				} else {
					Intent intent = new Intent(Intent.ACTION_SEND);
					intent.setType("text/plain");
					intent.putExtra(Intent.EXTRA_TEXT, result);
					startActivity(intent);
				}
			}

		}).execute(pastebinAPIKey, getTextToShare());
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater
				.inflate(R.layout.step_final_results, container, false);

		resultsView = (TextView) v.findViewById(R.id.final_results_output);

		if (secondarySubstitutionDictionary.getProductions().size() > 0) {
			startRandomSubstitution();
		} else {
			StringBuffer outBuf = new StringBuffer();
			for (String word : outList) {
				outBuf.append(word);
				outBuf.append(" ");
			}
			resultsView.setText(outBuf);
		}
		return v;
	}

	/**
	 * Starts the substitution process.
	 */
	private void startRandomSubstitution() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				System.out.println(secondarySubstituteList);
				System.out.println(secondarySubstitutionDictionary
						.getProductions());
				System.out.println(secondarySubstitutionDictionary
						.getProductionCategories());

				SharedPreferences mPrefs = PreferenceManager
						.getDefaultSharedPreferences(getActivity());
				int numRecurrences = Integer.parseInt(mPrefs.getString(
						"com.therandoms.rtgdroid.num_recurrences",
						String.valueOf(DEFAULT_RECURRENCES)));
				if (numRecurrences <= 0) {
					numRecurrences = DEFAULT_RECURRENCES;
				}
				final int recurrenceCount = numRecurrences;
				// do we randomly handle production categories as terminal
				// symbols?
				final boolean randomlyHandleCategory = mPrefs
						.getBoolean(
								"com.therandoms.rtgdroid.randomly_handle_production_category",
								false);

				// make the text
				secondarySubstitutionDictionary.generateText(
						secondarySubstituteList, generatedList, randomlyHandleCategory,
						recurrenceCount);

				final StringBuffer outBuf = new StringBuffer();
				for (String word : generatedList) {
					outBuf.append(word);
					outBuf.append(" ");
				}
				System.out.println(generatedList);
				// show the text on the ui thread.
				(new Handler(Looper.getMainLooper())).post(new Runnable() {

					@Override
					public void run() {
						resultsView.setText(outBuf.toString());
					}
				});

			}
		}).start();
	}

}
